package cn.lyjuan.android.demofive.view;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;

/**
 * Created by chad on 03/11/2017.
 */

public class ViewHolder
{
    /**
     * 用来初始化View对象
     */
    public static View inflater(LayoutInflater layoutInflater, View convertView, int resource)
    {
        View view = convertView;
        if (null == view)
            view = layoutInflater.inflate(resource, null);

        return view;
    }

    /**
     * 用来缓存控件，优化加载
     *
     * @param view itemView的布局
     * @param id   itemView布局中需要缓存控件的id
     * @return 缓存后的控件（textView、imageView...等控件）
     */
    public static <T extends View> T get(View view, int id)

    {
        // 获取itemView的ViewHolder对象，并将其转型为SparseArray<View>
        SparseArray<View> viewHolder = null == view.getTag() ? new SparseArray<View>() : (SparseArray<View>) view.getTag();

        view.setTag(viewHolder);

        // 根据控件的id获取itemView布局的控件
        View childView = viewHolder.get(id);
        if (childView == null)
        {
            // 如果还没有缓存该控件，那么就根据itemView找到该控件
            childView = view.findViewById(id);
            // 缓存该控件
            viewHolder.put(id, childView);
        }
        // 返回缓存好的控件
        return (T) childView;
    }
}
